package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.CommNumberStatBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@SuppressWarnings("serial")
@Component
@Scope("prototype")
@Namespace("/commNumberStat")
public class CommNumberStatAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(CommNumberStatAction.class);
	private CommNumberStatSearchCondtion searchCondition;
	@Autowired
	IPowerInfoService iPowerInfoService;
	@Autowired
	private IPageService  pageService;
	
	private InputStream excelFile;
	
	@Autowired
	private IExcelService excelService;
//	Operators op = new Operators();
	/**
	 * 跳转页面
	 * @return
	 */
	@Action(value="init",results={ @Result(name="success",location="/pages/commNum/CommNumberStat.jsp")})
	public String init(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(!(op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
				    ||op.getRoleType().equals(Role.SYSTEM.getCode())
			   	    ||op.getId()==40001 
			   	    ||op.getId()==1)){
				addActionError("无权限访问!!!");
				return ERROR;
			}		 
		}catch (Exception e) {
			logger.info("查询数据异常："+e);
			addActionError(e.getMessage());
			return ERROR;
		}	   
		return SUCCESS;
	}
	
	/**h
	 * 商户数量统计查询
	 */
	@Action(value="queryCommNumberStat",results={@Result(name="success",location="/pages/commNum/CommNumberStat.jsp")})
	public String queryCommNumberStat() {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getId()==40001 || op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
		if(searchCondition==null){
			searchCondition=(CommNumberStatSearchCondtion)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new CommNumberStatSearchCondtion();
			}
		}
		try {
			searchCondition.setId(op.getId());
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
				List<CommNumberStatBean> cclist=new ArrayList<CommNumberStatBean>();
				//查询
				dealWith(cclist, searchRsList);
			
			getRequest().setAttribute("cclist", cclist);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询商终明细数据异常："+e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
		addActionError("无权限访问!!!");
		return ERROR;	
	}
		
	
	/**
	 * 导出
	 * @Title: queryCommNumberDetail
	 * @return
	 * @author JC
	 * @date: 2018年1月29日 
	 *
	 */
	@Action(value="queryCommNumberDetail",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/commNum/CommNumberStat.jsp") }) 
	public String queryCommNumberDetail(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		logger.info("导出商户数量统计开始");
		
		if(searchCondition==null){
			searchCondition=(CommNumberStatSearchCondtion)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new CommNumberStatSearchCondtion();
			}
		}
		try {
			searchCondition.setId(op.getId());
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<CommNumberStatBean> ccList=new ArrayList<CommNumberStatBean>();
			dealWith(ccList,searchRsList);
			logger.info("rows:" + rows + "searchRsList.size():"+ searchRsList.size());
			SXSSFWorkbook work=excelService.exportCommNumber(ccList,searchCondition.getMinDate(),searchCondition.getMaxDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出商户数量统计结束");
		} catch (Exception e) {
			logger.info("导出商户数量统计开始："+e);
		}
		return SUCCESS;
	}
	
	private List<CommNumberStatBean> dealWith(List<CommNumberStatBean> cclist,List<Object> searchRsList){
		StringBuffer sb = new StringBuffer();
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				CommNumberStatBean comm = new CommNumberStatBean();
				comm.setCompanyName(Constance.Null2EmptyTrim(obj[0]));
				comm.setCommNumber(Constance.Null2EmptyTrim(obj[1]));
				comm.setSunPieceNumber(Constance.Null2EmptyTrim(obj[2]));
				comm.setAreaCode(Constance.Null2EmptyTrim(obj[3]));
				if(searchCondition.getMinDate().equals(searchCondition.getMaxDate())){
					comm.setMinDate(searchCondition.getMinDate());
				}else{
					comm.setMinDate(searchCondition.getMinDate()+"-"+searchCondition.getMaxDate());
				}
				
				sb.setLength(0);
				cclist.add(comm);
			}
		}
		return cclist;
	}	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_COMM_NUMBER_STAT, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (CommNumberStatSearchCondtion)getSession().getAttribute(SEARCH_SESSION_COMM_NUMBER_STAT);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public String getExcelName() {
		String excelName="商户数量统计"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}



	public CommNumberStatSearchCondtion getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(CommNumberStatSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}


}
